<template>
  <div class="news-editor-page">
    <div class="page-header">
      <h1 class="page-title">{{ isEdit ? '编辑新闻' : '发布新闻' }}</h1>
      <div class="header-actions">
        <a-space>
          <a-button @click="goBack">取消</a-button>
          <a-button type="primary" @click="saveAsDraft" :loading="saving">
            保存草稿
          </a-button>
          <a-button type="primary" @click="publishNews" :loading="publishing">
            {{ isEdit ? '更新' : '发布' }}
          </a-button>
        </a-space>
      </div>
    </div>
    
    <div class="editor-container">
      <a-form
        :model="newsForm"
        name="news-form"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 20 }"
        @finish="onFinish"
      >
        <a-form-item
          label="标题"
          name="title"
          :rules="[{ required: true, message: '请输入新闻标题' }]"
        >
          <a-input 
            v-model:value="newsForm.title"
            placeholder="请输入新闻标题"
            :maxlength="100"
            show-count
          />
        </a-form-item>
        
        <a-form-item
          label="分类"
          name="categoryId"
          :rules="[{ required: true, message: '请选择新闻分类' }]"
        >
          <a-select
            v-model:value="newsForm.categoryId"
            placeholder="请选择新闻分类"
          >
          <a-select-option 
              v-for="category in categories" 
              :key="category.id" 
              :value="category.id"
              :loading="categoriesLoading"
            >
              {{ category.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        
        <a-form-item
          label="摘要"
          name="summary"
        >
          <a-textarea 
            v-model:value="newsForm.summary"
            placeholder="请输入新闻摘要"
            :auto-size="{ minRows: 2, maxRows: 6 }"
            :maxlength="200"
            show-count
          />
        </a-form-item>
        
        <!-- <a-form-item
          label="作者"
          name="author"
          :rules="[{ required: true, message: '请输入作者' }]"
        >
          <a-input 
            v-model:value="newsForm.author"
            placeholder="请输入作者"
          />
        </a-form-item> -->
        
        <a-form-item
          label="封面图片"
          name="imageUrl"
        >
          <div class="upload-container">
            <a-upload
              v-model:file-list="fileList"
              list-type="picture-card"
              :before-upload="beforeUpload"
              @preview="handlePreview"
            >
              <div v-if="fileList.length < 1">
                <plus-outlined />
                <div style="margin-top: 8px">上传</div>
              </div>
            </a-upload>
            <a-modal
              :visible="previewVisible"
              :title="previewTitle"
              :footer="null"
              @cancel="previewVisible = false"
            >
              <img alt="预览图片" style="width: 100%" :src="previewImage" />
            </a-modal>
          </div>
          <div class="upload-tip">建议上传16:9比例的图片，大小不超过2MB</div>
        </a-form-item>
        
        <!-- <a-form-item
          label="视频链接"
          name="videoUrl"
        >
          <a-input 
            v-model:value="newsForm.videoUrl"
            placeholder="请输入视频链接（选填）"
          />
        </a-form-item> -->
        
        <a-form-item
          label="标签"
          name="tags"
        >
          <a-select
            v-model:value="newsForm.tags"
            mode="tags"
            placeholder="请输入标签，按回车分隔"
            :token-separators="[',']"
          ></a-select>
        </a-form-item>
        
        <!-- 新增：首页轮播新闻复选框 -->
        <a-form-item
          label="设置选项"
          name="options"
        >
          <div class="checkbox-group">
            <a-checkbox v-model:checked="newsForm.isTop" :value="1">
              置顶新闻
            </a-checkbox>
            <a-checkbox v-model:checked="newsForm.isFeatured" :value="1">
              推荐新闻
            </a-checkbox>
          </div>
        </a-form-item>

        <a-form-item
          label="内容"
          name="content"
          :rules="[{ required: true, message: '请输入新闻内容' }]"
        >
          <div class="editor-wrapper">
            <!-- 这里使用简化的富文本编辑器，实际项目中可以集成完整的编辑器如 TinyMCE, CKEditor 等 -->
            <a-textarea 
              v-model:value="newsForm.content"
              placeholder="请输入新闻内容"
              :auto-size="{ minRows: 15, maxRows: 20 }"
            />
          </div>
        </a-form-item>
      </a-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import request from '../../utils/request' // 导入请求工具

const route = useRoute()
const router = useRouter()

// 判断是编辑还是新建
const isEdit = computed(() => {
  return route.params.id !== undefined
})

// 分类数据
const categories = ref([])

// 表单数据
const newsForm = reactive({
  id: null,
  title: '',
  categoryId: null,
  summary: '',
  authorName: '',
  coverImage: '',
  tags: '',
  content: '',
  isTop: 0,
  isFeatured: 0
})

// 上传图片相关状态
const fileList = ref([])
const previewVisible = ref(false)
const previewImage = ref('')
const previewTitle = ref('')

// 保存和发布状态
const saving = ref(false)
const publishing = ref(false)
const categoriesLoading = ref(false)

// 获取分类列表
const fetchCategories = async () => {
  categoriesLoading.value = true
  try {
    const response = await request.get('/categories/list')
    if (response.code === 200) {
      categories.value = response.data
    } else {
      message.error('获取分类列表失败')
    }
  } catch (error) {
    message.error('获取分类列表失败，请稍后再试')
    console.error('获取分类列表失败:', error)
  } finally {
    categoriesLoading.value = false
  }
}

// 图片上传前处理
const beforeUpload = async (file) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
  if (!isJpgOrPng) {
    message.error('只能上传JPG或PNG格式的图片!')
    return false
  }
  
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    message.error('图片大小不能超过2MB!')
    return false
  }
  
  // 调用后端上传接口
  try {
    const formData = new FormData()
    formData.append('file', file)
    
    const response = await request.post('/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    
    if (response.code === 200) {
      // 上传成功，设置表单中的图片URL
      newsForm.coverImage = response.data
      
      message.success('图片上传成功')
    } else {
      message.error('图片上传失败')
    }
  } catch (error) {
    message.error('图片上传失败，请稍后再试')
    console.error('图片上传失败:', error)
  }
  
  return false // 阻止 antd 的默认上传行为
}

// 图片预览
const handlePreview = (file) => {
  previewImage.value = file.url || file.preview
  previewVisible.value = true
  previewTitle.value = file.name || file.url.substring(file.url.lastIndexOf('/') + 1)
}

// 获取新闻详情（编辑模式）
const fetchNewsDetail = async () => {
  if (!isEdit.value) return
  
  try {
    // 实际项目中应该调用API
    const response = await request.get(`/news/detail/${route.params.id}`)
    const data = response.data
    Object.assign(newsForm, data)
    
    // 设置图片预览
    if (data.coverImage) {
      fileList.value = [{
        uid: '-1',
        name: 'news-image.jpg',
        status: 'done',
        url: data.coverImage
      }]
    }
    
  } catch (error) {
    message.error('获取新闻详情失败，请稍后再试')
    console.error('获取新闻详情失败:', error)
  }
}

// 保存为草稿
const saveAsDraft = async () => {
  saving.value = true
  try {
    // 实际项目中应该调用API
    // const response = await axios.post('/api/admin/news/draft', newsForm)
    const response = await request.post('/news/', newsForm) // 调用保存接口
    if (response.code === 200) {
      categories.value = response.data
    } else {
      message.error('保存失败')
    }
    // 根据您的后端返回结果进行处理，这里假设成功后直接提示并跳转
    message.success('草稿保存成功')
    router.push('/admin/news')
  } catch (error) {
    message.error('保存失败，请稍后再试')
    console.error('保存失败:', error)
  } finally {
    saving.value = false
  }
}

// 发布新闻
const publishNews = async () => {
  // 表单验证
  if (!newsForm.title || !newsForm.categoryId || !newsForm.content) {
    message.error('请填写必填项')
    return
  }
  
  publishing.value = true
  try {
    // 实际项目中应该调用API
    // const url = isEdit.value ? `/api/admin/news/${route.params.id}` : '/api/admin/news'
    // const method = isEdit.value ? 'put' : 'post'
    // const response = await axios[method](url, newsForm)
    
    // 模拟发布过程
    const response = await request.post('/news/publish', newsForm) // 调用保存接口
    if (response.code === 200) {
      categories.value = response.data
    } else {
      message.error('发布失败')
    }
    // 根据您的后端返回结果进行处理，这里假设成功后直接提示并跳转
    message.success('发布成功')
    router.push('/admin/news')
  } catch (error) {
    message.error(isEdit.value ? '更新失败' : '发布失败')
    console.error(isEdit.value ? '更新失败' : '发布失败', error)
  } finally {
    publishing.value = false
  }
}

// 表单提交
const onFinish = (values) => {
  publishNews()
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 组件挂载时获取数据
onMounted(() => {
  fetchCategories() // 先获取分类数据
  fetchNewsDetail()
})
</script>

<style scoped>
.news-editor-page {
  padding-bottom: 30px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  font-size: 24px;
  font-weight: bold;
  color: #003366;
  margin: 0;
}

.editor-container {
  background-color: #fff;
  border-radius: 4px;
  padding: 24px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.upload-container {
  display: flex;
  align-items: center;
}

.upload-tip {
  color: #999;
  font-size: 12px;
  margin-top: 8px;
}

.editor-wrapper {
  border: 1px solid #d9d9d9;
  border-radius: 2px;
  padding: 5px;
}

.editor-tip {
  color: #999;
  font-size: 12px;
  margin-top: 8px;
  text-align: right;
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .header-actions {
    margin-top: 16px;
  }
  
  .editor-container :deep(.ant-form-item-label) {
    text-align: left;
  }
  
  .editor-container :deep(.ant-col-4) {
    flex: 0 0 100%;
    max-width: 100%;
  }
  
  .editor-container :deep(.ant-col-20) {
    flex: 0 0 100%;
    max-width: 100%;
  }
}
</style>